package handler

import (
	"admin-nexus-backend/internal/dto"
	"admin-nexus-backend/internal/service"
	"admin-nexus-backend/pkg/response"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type AttachmentHandler struct {
	attachmentService *service.AttachmentService
}

func NewAttachmentHandler(db *gorm.DB) *AttachmentHandler {
	return &AttachmentHandler{
		attachmentService: service.NewAttachmentService(db),
	}
}

// GetAttachmentList 获取附件列表
// @Summary 获取附件列表
// @Description 分页查询附件列表
// @Tags 附件管理
// @Security ApiKeyAuth
// @Produce json
// @Param page query int true "页码"
// @Param pageSize query int true "每页数量"
// @Param category query string false "类别"
// @Param filename query string false "文件名"
// @Param imageType query string false "文件类型"
// @Param storage query string false "存储引擎"
// @Param mimetype query string false "MIME类型"
// @Param minFilesize query int false "最小文件大小"
// @Param maxFilesize query int false "最大文件大小"
// @Param startTime query string false "开始时间"
// @Param endTime query string false "结束时间"
// @Success 200 {object} response.Response{data=dto.PageResult}
// @Router /api/v1/attachments [get]
func (h *AttachmentHandler) GetAttachmentList(c *gin.Context) {
	var params dto.AttachmentQueryParams
	if err := c.ShouldBindQuery(&params); err != nil {
		response.Error(c, "参数错误")
		return
	}

	list, total, err := h.attachmentService.GetList(&params)
	if err != nil {
		response.Error(c, "获取附件列表失败")
		return
	}

	response.SuccessWithData(c, dto.PageResult{
		List:     list,
		Total:    total,
		Page:     params.Page,
		PageSize: params.PageSize,
	})
}

// GetAttachment 获取附件详情
// @Summary 获取附件详情
// @Description 根据ID获取附件详细信息
// @Tags 附件管理
// @Security ApiKeyAuth
// @Produce json
// @Param id path int true "附件ID"
// @Success 200 {object} response.Response{data=model.Attachment}
// @Router /api/v1/attachments/{id} [get]
func (h *AttachmentHandler) GetAttachment(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.Error(c, "无效的ID")
		return
	}

	attachment, err := h.attachmentService.GetByID(uint(id))
	if err != nil {
		response.Error(c, err.Error())
		return
	}

	response.SuccessWithData(c, attachment)
}

// CreateAttachment 创建附件
// @Summary 创建附件
// @Description 创建新附件记录
// @Tags 附件管理
// @Security ApiKeyAuth
// @Accept json
// @Produce json
// @Param request body dto.AttachmentCreateRequest true "附件信息"
// @Success 200 {object} response.Response{data=model.Attachment}
// @Router /api/v1/attachments [post]
func (h *AttachmentHandler) CreateAttachment(c *gin.Context) {
	var req dto.AttachmentCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, "参数错误")
		return
	}

	attachment, err := h.attachmentService.Create(&req)
	if err != nil {
		response.Error(c, "创建附件失败")
		return
	}

	response.SuccessWithData(c, attachment)
}

// UpdateAttachment 更新附件
// @Summary 更新附件
// @Description 更新附件信息
// @Tags 附件管理
// @Security ApiKeyAuth
// @Accept json
// @Produce json
// @Param id path int true "附件ID"
// @Param request body dto.AttachmentUpdateRequest true "附件信息"
// @Success 200 {object} response.Response{data=model.Attachment}
// @Router /api/v1/attachments/{id} [put]
func (h *AttachmentHandler) UpdateAttachment(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.Error(c, "无效的ID")
		return
	}

	var req dto.AttachmentUpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, "参数错误")
		return
	}

	attachment, err := h.attachmentService.Update(uint(id), &req)
	if err != nil {
		response.Error(c, err.Error())
		return
	}

	response.SuccessWithData(c, attachment)
}

// DeleteAttachment 删除附件
// @Summary 删除附件
// @Description 删除附件（软删除）
// @Tags 附件管理
// @Security ApiKeyAuth
// @Produce json
// @Param id path int true "附件ID"
// @Success 200 {object} response.Response
// @Router /api/v1/attachments/{id} [delete]
func (h *AttachmentHandler) DeleteAttachment(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.Error(c, "无效的ID")
		return
	}

	if err := h.attachmentService.Delete(uint(id)); err != nil {
		response.Error(c, err.Error())
		return
	}

	response.SuccessWithData(c, nil)
}

// BatchDeleteAttachments 批量删除附件
// @Summary 批量删除附件
// @Description 批量删除多个附件
// @Tags 附件管理
// @Security ApiKeyAuth
// @Accept json
// @Produce json
// @Param ids body []uint true "附件ID列表"
// @Success 200 {object} response.Response
// @Router /api/v1/attachments/batch-delete [post]
func (h *AttachmentHandler) BatchDeleteAttachments(c *gin.Context) {
	var ids []uint
	if err := c.ShouldBindJSON(&ids); err != nil {
		response.Error(c, "参数错误")
		return
	}

	if err := h.attachmentService.BatchDelete(ids); err != nil {
		response.Error(c, err.Error())
		return
	}

	response.SuccessWithData(c, nil)
}

// UploadFile 上传文件
// @Summary 上传文件
// @Description 上传文件并创建附件记录
// @Tags 附件管理
// @Security ApiKeyAuth
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "文件"
// @Param category formData string false "类别"
// @Param extparam formData string false "透传数据"
// @Success 200 {object} response.Response{data=dto.AttachmentUploadResponse}
// @Router /api/v1/attachments/upload [post]
func (h *AttachmentHandler) UploadFile(c *gin.Context) {
	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		response.Error(c, "请选择要上传的文件")
		return
	}

	// 获取可选参数
	category := c.PostForm("category")
	extparam := c.PostForm("extparam")

	// 上传文件
	attachment, err := h.attachmentService.Upload(file, category, extparam)
	if err != nil {
		response.Error(c, "上传文件失败: "+err.Error())
		return
	}

	// 返回响应
	response.SuccessWithData(c, dto.AttachmentUploadResponse{
		ID:       attachment.ID,
		URL:      attachment.URL,
		Filename: attachment.Filename,
		Filesize: attachment.Filesize,
		Mimetype: attachment.Mimetype,
	})
}

// GetCategories 获取所有类别
// @Summary 获取所有类别
// @Description 获取附件的所有类别列表
// @Tags 附件管理
// @Security ApiKeyAuth
// @Produce json
// @Success 200 {object} response.Response{data=[]string}
// @Router /api/v1/attachments/categories [get]
func (h *AttachmentHandler) GetCategories(c *gin.Context) {
	categories, err := h.attachmentService.GetCategories()
	if err != nil {
		response.Error(c, "获取类别列表失败")
		return
	}

	response.SuccessWithData(c, categories)
}

// GetStorageEngines 获取所有存储引擎
// @Summary 获取所有存储引擎
// @Description 获取附件的所有存储引擎列表
// @Tags 附件管理
// @Security ApiKeyAuth
// @Produce json
// @Success 200 {object} response.Response{data=[]string}
// @Router /api/v1/attachments/storage-engines [get]
func (h *AttachmentHandler) GetStorageEngines(c *gin.Context) {
	engines, err := h.attachmentService.GetStorageEngines()
	if err != nil {
		response.Error(c, "获取存储引擎列表失败")
		return
	}

	response.SuccessWithData(c, engines)
}
